<template>
  <x-dialog :title="title" :show.sync="visible" v-if="visible" :before-close="handleClose" width="40%">
    <el-form :model="params" :rules="rules" ref="params" class="demo-form-inline" label-position="top">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.name')" prop="name">
            <el-input
              v-model="params.name"
              :placeholder="$t('resourceAdmin.datasource.placeHolderInput')"
              clearable
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.driverClassName')" prop="driverClassName">
            <el-input
              v-model="params.driverClassName"
              :placeholder="$t('resourceAdmin.datasource.placeHolderInput')"
              clearable
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.dsName')" prop="dsName">
            <el-input
              v-model="params.dsName"
              :placeholder="$t('resourceAdmin.datasource.placeHolderInput')"
              clearable
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.dsType')" prop="dsType">
            <x-select
              v-model="params.dsType"
              :options="dictOptions['upms_datasource.ds_type']"
              style="width: 100%"
              :placeholder="$t('resourceAdmin.datasource.placeHolderSelect')"
              clearable
            ></x-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.username')" prop="username">
            <el-input
              v-model="params.username"
              auto-complete="new-password"
              :placeholder="$t('resourceAdmin.datasource.placeHolderInput')"
              clearable
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.password')" prop="password" v-if="!params?.id">
            <el-input
              type="password"
              v-model="params.password"
              auto-complete="new-password"
              :placeholder="$t('resourceAdmin.datasource.placeHolderInput')"
              clearable
              maxlength="100"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.url')" prop="url">
            <el-input
              v-model="params.url"
              :placeholder="$t('resourceAdmin.datasource.placeHolderInput')"
              clearable
              maxlength="300"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('resourceAdmin.datasource.state')" prop="state">
            <x-radio-group :list-data="dictOptions['system.state']" v-model="params.state"></x-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer">
      <el-button @click="handleClose"> {{ $t('common.cancel') }} </el-button>
      <el-button
        type="primary"
        @click="
          loading = true
          handleSubmit()
        "
        :loading="loading"
      >
        {{ $t('common.save') }}
      </el-button>
    </span>
  </x-dialog>
</template>
<script>
  import { cloneDeep, omit, throttle, checkEmail, encrypt } from '@package/utils'
  import { apiPostAddDatasource, apiPutEditDatasource } from '../api/datasource'
  import { EnumApiCode } from '../../../../../../globalEnum'

  export default {
    props: {
      dictOptions: {
        type: Object
      }
    },
    data() {
      return {
        visible: false,
        loading: false,
        title: this.$t('resourceAdmin.datasource.add'),
        params: {
          dsName: '',
          dsType: '',
          username: '',
          password: '',
          driverClassName: '',
          name: '',
          state: '1',
          url: ''
        },
        editPwd: false,
        rules: {
          dsName: [
            { required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'blur' },
            { min: 1, max: 100, message: this.$t('resourceAdmin.datasource.inputRulesProm'), trigger: 'blur' }
          ],
          dsType: [{ required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'blur' }],
          username: [
            { required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'blur' },
            { min: 1, max: 100, message: this.$t('resourceAdmin.datasource.inputRulesProm'), trigger: 'blur' }
          ],
          password: [
            { required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'blur' }
          ],
          name: [{ required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'blur' }],
          state: [
            { required: true, message: this.$t('resourceAdmin.datasource.placeHolderSelect'), trigger: 'change' }
          ],
          driverClassName: [
            { required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'change' }
          ],
          url: [{ required: true, message: this.$t('resourceAdmin.datasource.placeHolderInput'), trigger: 'blur' }]
        }
      }
    },
    watch: {
      'params.password': {
        handler(val) {
          if (val === '') {
            this.editPwd = true
          }
        },
        deep: true
      }
    },
    methods: {
      handleOpen(info) {
        this.visible = true
        if (info?.id) {
          this.title = this.$t('common.edit')
          this.$nextTick(() => {
            this.params = Object.assign(this.params, cloneDeep(info))
            this.params.state += ''
            this.editPwd = false
            this.params.password = '......'
          })
          return
        }
        this.title = this.$t('resourceAdmin.datasource.add')
      },
      validateEmail(rule, value, callback) {
        if (value && value !== '' && !checkEmail(value)) {
          callback(new Error(this.$t('system.user.EmailAddresses')))
        } else {
          callback()
        }
      },
      handleSubmit: throttle(function () {
        this.loading = true
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = {
              ...this.params,
              password: this.params.id ? null : encrypt(this.params.password)
            }
            try {
              const { code, msg } = this.params.id
                ? await apiPutEditDatasource(param)
                : await apiPostAddDatasource(param)
              this.loading = false
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleClose()
                this.$emit('handleSuccess')
              } else {
                this.$message.error(msg)
              }
            } finally {
              this.loading = false
            }
          } else {
            this.loading = false
            return false
          }
        })
      }, 1000),
      handleClose() {
        this.$refs.params.resetFields()
        this.params = omit(this.params, 'id')
        this.loading = false
        this.visible = false
      }
    }
  }
</script>
<style lang="scss" scoped>
  ::v-deep.el-input.is-disabled .el-input__inner,
  ::v-deep.el-textarea.is-disabled .el-textarea__inner {
    cursor: auto;
    color: #606266;
  }
</style>
